package testcase;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class HttpClientWithPostParam {

    @Test
    public void testName() throws IOException {
        // 获取连接客户端工具
        DefaultHttpClient httpClient = new DefaultHttpClient();

        String entityStr = null;
        HttpResponse response = null;

            // 创建POST请求对象
            HttpPost httpPost = new HttpPost("http://localhost:12306/mockPostwithparam");

            /*
             * 添加请求参数
             */
            // 创建请求参数

        //添加除了json格式以外的任何参数
            List<NameValuePair> list = new LinkedList<NameValuePair>();
            BasicNameValuePair param1 = new BasicNameValuePair("name", "chengliang");
            BasicNameValuePair param2 = new BasicNameValuePair("age", "23");
            list.add(param1);
            list.add(param2);
            // 使用URL实体转换工具
            UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entityParam);

            /*
             * 添加请求头信息
             */
            // 浏览器表示
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");

            // System.out.println(Arrays.toString(response.getAllHeaders()));



        // 打印响应内容
        System.out.println(entityStr);

    }
}
